import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { ApesMessageService } from '@shared/apes/message';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { PurchaseService } from '../purchase.service';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApiService } from '@core/services/http/api.service';
import { endOfMonth, format, startOfMonth } from 'date-fns';
import {AllModules, Module} from "@ag-grid-enterprise/all-modules";


@Component({
  selector: 'comprehensive-analysis',
  templateUrl: './comprehensive-analysis.component.html',
  styleUrls: ['../purchase-report-form.scss'],
})
export class ComprehensiveAnalysisComponent implements OnInit {
  /** 按钮相关 **/
  buttonBar = [
    { hide: true, style: 'default', label: '查询', id: 'action_query' },
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  modules:Module[] =AllModules
  rowData: any;
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  height: any = window.innerHeight - 220 + 'px';

  timeList: any = [];                 // 审核日期
  supplier: any;
  supplierID: string;
  pdata = { 'START_RQ': '', 'END_RQ': '', 'GYSID': '' };

  but = [
    { value: 7 },
    { value: 30 },
    { value: 90 },
  ];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private pa: PurchaseService,
              private userAuthService: UserAuthService) {
    this.gridInit();
  }

  ngOnInit() {
    this.initialization();
  }

  // gird初始化
  gridInit() {
    this.columnDefs = [
      {
        children: [{ headerName: '行标签', field: 'GYSMC', width: 200, pinned: 'left' }],
      },
      {
        headerName: '入库时效',
        children: [
          { headerName: '总入库数/个', field: 'RKZSL', width: 110 },
          { headerName: '总入库占比', field: 'RKZZB', width: 110},
          { headerName: '1小时入库', field: 'ONE_HOURS', width: 110 },
          { headerName: '1小时占比', field: 'ONE_RATIO', width: 110},
          { headerName: '1-2小时入库', field: 'ONE_TWO_HOURS', width: 110 },
          { headerName: '1-2小时占比', field: 'ONE_TWO_RATIO', width: 110},
          { headerName: '2-3小时入库', field: 'TWO_TO_THREE_HOURS', width: 110 },
          { headerName: '2-3小时占比', field: 'TWO_TO_THREE_RATIO', width: 110 },
          { headerName: '3-4小时入库', field: 'THREE_TO_FOUR_HOURS', width: 110 },
          { headerName: '3-4小时占比', field: 'THREE_TO_FOUR_RATIO', width: 110 },
          { headerName: '超4小时入库', field: 'MORE_FOUR_HOURS', width: 110 },
          { headerName: '超4小时占比', field: 'MORE_FOUR_RATIO', width: 110 },
        ],
      },
      {
        headerName: '品牌件',
        children: [
          { headerName: '报价数', field: 'PP_BJS', width: 100 },
          { headerName: '推荐数', field: 'PP_TJS', width: 100 },
          { headerName: '推荐率', field: 'PP_ZB', width: 100 },
        ],
      },
      {
        headerName: '原厂件',
        children: [
          { headerName: '报价数', field: 'YC_BJS', width: 100 },
          { headerName: '推荐数', field: 'YC_TJS', width: 100 },
          { headerName: '推荐率', field: 'YC_ZB', width: 100 },
        ],
      },
      {
        headerName: '名牌件',
        children: [
          { headerName: '报价数', field: 'MP_BJS', width: 100 },
          { headerName: '推荐数', field: 'MP_TJS', width: 100 },
          { headerName: '推荐率', field: 'MP_ZB', width: 100 },
        ],
      },
      {
        headerName: '合计',
        children: [
          { headerName: '报价数', field: 'TOTAL_BJS', width: 100 },
          { headerName: '推荐数', field: 'TOTAL_TJS', width: 100 },
          { headerName: '推荐率', field: 'TOTAL_ZB', width: 100 },
        ],
      },
      {
        headerName: '报价合计',
        children: [
          { headerName: '总需报价数', field: 'TSBJS', width: 100 },
          { headerName: '完成报价', field: 'WCBJ', width: 100 },
          { headerName: '超时', field: 'CSSL', width: 100 },
          { headerName: '超时率', field: 'CSL', width: 100 },
          { headerName: '未报价', field: 'WWCBJ', width: 100 },
          { headerName: '未报价率', field: 'WWCBJL', width: 100 },
        ],
      },
      {
        headerName: '返厂率',
        children: [
          { headerName: '总返厂数量', field: 'FCZSL', width: 100 },
          { headerName: '返厂率', field: 'FCL', width: 100 },
        ],
      },
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: false,
      suppressCsvExport: false,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = this.gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        let now = params.data.CS;
        return now < 0;
      },
      // 超时
      'grid-tab-warning': function(params) {
        let now = params.data.CS;
        return now >= 0;
      },
    };
  }

  // 初始化
  initialization() {
    // 默认 请求 当天 数据
    this.timeList = this.pa.dayChang(0);
    this.pa.getSupplierData().then(value => {
      this.supplier = value;
    });
  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.queryData();
      } else if (data.id === 'action_export') {
        this.action_export();
      }
    }
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const params = {
      columnGroups: true,
      sheetName: 'sheet1',
      fileName: '供应商综合分析',
    };
    this.gridOptions.api.exportDataAsExcel(params);
  }
  queryData() {
    if (JSON.stringify(this.timeList) !== '[]') {
      this.timeList[0] = format(this.timeList[0], 'YYYY-MM-DD');
      this.timeList[1] = format(this.timeList[1], 'YYYY-MM-DD');
    }
    if (JSON.stringify(this.timeList) !== '[]') {
      this.pdata.START_RQ = this.timeList[0];
      this.pdata.END_RQ = this.timeList[1];
      this.pdata.GYSID = this.supplierID;
      this.getTablesData();
    } else {
      this.msg.error('日期不能为空！');
    }
  }

  _submit($event) {
    this.timeList = this.pa.dayChang($event);
  }

  getTablesData() {
    const data = { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryAnalysisReport', 'pdata': this.pdata };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let list: any = JSON.parse(result.obj);
            for(let item of list) {
              item['RKZZB'] = item['RKZZB'] + '%';
              item['ONE_RATIO'] = item['ONE_RATIO'] + '%';
              item['ONE_TWO_RATIO'] = item['ONE_TWO_RATIO'] + '%';
              item['TWO_TO_THREE_RATIO'] = item['TWO_TO_THREE_RATIO'] + '%';
              item['THREE_TO_FOUR_RATIO'] = item['THREE_TO_FOUR_RATIO'] + '%';
              item['MORE_FOUR_RATIO'] = item['MORE_FOUR_RATIO'] + '%';
              item['PP_ZB'] = item['PP_ZB'] + '%';
              item['YC_ZB'] = item['YC_ZB'] + '%';
              item['MP_ZB'] = item['MP_ZB'] + '%';
              item['TOTAL_ZB'] = item['TOTAL_ZB'] + '%';
              item['CSL'] = item['CSL'] + '%';
              item['WWCBJL'] = item['WWCBJL'] + '%';
              item['FCL'] = item['FCL'] + '%';
            }
            this.rowData = list;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

}
